package com.itheima.controller;

import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

/**
 * @Description:
 * @Version: V1.0
 */
@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {
    @Autowired
    private JedisPool jedisPool;
    //用户体检预约发送验证码
    @RequestMapping("/send4Order")
    public Result send4Order(String telephone){
        //先根据手机号,查询此手机号在30s内有没有发送过验证码(redis中此手机号是否有值)
        String code = jedisPool.getResource().get(telephone + RedisMessageConstant.SENDTYPE_ORDER + "VALIDATE");
        if (!StringUtils.isEmpty(code)) {
            return new Result(false,"30s内不能重复发送");
        }

        //随机生成4位数字验证码
        Integer validateCode = ValidateCodeUtils.generateValidateCode(4);
        //给用户发送验证码
        try {
            SMSUtils.sendShortMessage(SMSUtils.VALIDATE_CODE,telephone,validateCode.toString());
        } catch (ClientException e) {
            e.printStackTrace();
            //发送验证码失败
            return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
        }
        //将验证码保存进redis中5分钟
        jedisPool.getResource().setex(telephone+ RedisMessageConstant.SENDTYPE_ORDER,300,validateCode.toString());
        //保存一个30秒的验证码到redis供查询手机号
        jedisPool.getResource().setex(telephone+ RedisMessageConstant.SENDTYPE_ORDER+"VALIDATE",30,validateCode.toString());
        //验证码发送成功
        return new Result(true,MessageConstant.SEND_VALIDATECODE_SUCCESS);
    }
}
